<template>
  <div>
    <!-- 面包屑  -->
    <el-breadcrumb separator-class="el-icon-arrow-right">
      <el-breadcrumb-item :to="{ path: '/home' }">首页</el-breadcrumb-item>
      <el-breadcrumb-item>商品管理</el-breadcrumb-item>
      <el-breadcrumb-item>商品分类</el-breadcrumb-item>
    </el-breadcrumb>
    <!--  卡片视图  -->
    <el-card class="box-card">
      <el-row>
        <el-col>
          <el-button type="primary" @click="showAddCateDialog">添加分类</el-button>
        </el-col>
      </el-row>
      <!--  表格  -->
      <tree-table :data="cateList" :columns="columns" :selection-type="false"
                  :show-index="true" indent-index="'序号'" :expand-type="false"
                  :show-row-hover="false" border style="margin-top: 15px">
        <!--  是否有效  -->
        <template slot="isOk" slot-scope="scope">
          <i v-if="!scope.row.cat_deleted" class="el-icon-success" style="color: #2cee0d;font-size: 16px"></i>
          <i v-else class="el-icon-error" style="color: #ff283a;font-size: 16px"></i>
        </template>
        <!--  排序  -->
        <template slot="level" slot-scope="scope">
          <el-tag v-if="scope.row.cat_level === 0">一级</el-tag>
          <el-tag v-else-if="scope.row.cat_level === 1" type="success">二级</el-tag>
          <el-tag v-else type="warning">三级</el-tag>
        </template>
        <template slot="opt" slot-scope="scope">
          <el-button type="primary" icon="el-icon-edit" size="mini">编辑</el-button>
          <el-button type="danger" icon="el-icon-delete" size="mini" @click="deleteCate(scope.row.cat_id)">删除</el-button>
        </template>
      </tree-table>
      <!--  分页    -->
      <el-pagination
        @size-change="handleSizeChange"
        @current-change="handleCurrentChange"
        :current-page="queryInfo.pagenum"
        :page-sizes="[1, 2, 5, 10]"
        :page-size="queryInfo.pagesize"
        layout="total, sizes, prev, pager, next, jumper"
        :total="total">
      </el-pagination>
    </el-card>
    <!--  添加分类对话框    -->
    <el-dialog
      title="添加分类"
      :visible.sync="addCateDialogVisible"
      width="50%"
      @close="addCateDialogClose">
      <!--  内容主体区域    -->
      <el-form ref="addCateRef"
               :model="addCateForm"
               :rules="addCateRules"
               label-width="100px">
        <!-- 分类名称 -->
        <el-form-item label="分类名称" prop="cat_name">
          <el-input v-model="addCateForm.cat_name"></el-input>
        </el-form-item>
        <!-- 父级分类 -->
        <el-form-item label="父级分类">
          <el-cascader
            clearable
            change-on-select
            v-model="selectedKeys"
            :options="parentCateList"
            :props="cascaderProps"
            @change="parentCateChange"></el-cascader>
        </el-form-item>
      </el-form>
      <span slot="footer" class="dialog-footer">
        <el-button @click="addCateDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="addCate">确 定</el-button>
      </span>
    </el-dialog>
  </div>
</template>

<script>
  export default {
    name: 'Cate',
    data () {
      return {
        queryInfo: {
          type: 3,
          pagenum: 1,
          pagesize: 5
        },
        // 商品分类数组
        cateList: [],
        // 总分类条数
        total: 0,
        // tree-table列配置
        columns: [{
          label: '分类名称',
          prop: 'cat_name'
        }, {
          label: '是否有效',
          type: 'template',
          template: 'isOk'
        }, {
          label: '排序',
          type: 'template',
          template: 'level'
        }, {
          label: '操作',
          type: 'template',
          template: 'opt'
        }],
        // 添加分类对话框显示
        addCateDialogVisible: false,
        // 添加分类的表单数据对象
        addCateForm: {
          cat_name: '',
          // 父级分类的id
          cat_pid: 0,
          // 分类的等级，默认是1级分类
          cat_level: 0
        },
        // 添加分类校验规则
        addCateRules: {
          cat_name: [
            {
              required: true,
              message: '请输入分类名称',
              trigger: 'blur'
            }
          ]
        },
        // 父级分类数据列表，添加分类时级联选择框
        parentCateList: [],
        // 父级分类级联选择框配置
        cascaderProps: {
          expandTrigger: 'hover',
          value: 'cat_id',
          label: 'cat_name',
          children: 'children'
        },
        // 选中的父级分类id数组
        selectedKeys: []
      }
    },
    created () {
      this.getCateList()
    },
    methods: {
      // 商品分类数据获取
      async getCateList() {
        const { data: res } = await this.$http.get('categories', { params: this.queryInfo })
        if (res.meta.status !== 200) return this.$message.error('获取商品分类失败！')
        this.cateList = res.data.result
        this.total = res.data.total
      },
      handleSizeChange(newSize) {
        this.queryInfo.pagesize = newSize
        this.getCateList()
      },
      handleCurrentChange(newPage) {
        this.queryInfo.pagenum = newPage
        this.getCateList()
      },
      showAddCateDialog() {
        this.getParentCateList()
        this.addCateDialogVisible = true
      },
      // 添加分类对话框关闭事件
      addCateDialogClose() {
        // 重置表单
        this.$refs.addCateRef.resetFields()
        // 重置cascade组件绑定值
        this.selectedKeys = []
        this.addCateForm.cat_level = 0
        this.addCateForm.cat_pid = 0
      },
      // 获取父级分类的数据列表
      async getParentCateList() {
        const { data: res } = await this.$http.get('categories', { params: { type: 2 } })
        if (res.meta.status !== 200) return this.$message.error('获取父级分类数据失败！')
        this.parentCateList = res.data
        console.log(this.parentCateList)
      },
      // 级联选择框选中事件
      parentCateChange() {
        console.log(this.selectedKeys)
        if (this.selectedKeys.length) {
          // 设置form表单的父级分类id
          const { length } = this.selectedKeys
          this.addCateForm.cat_pid = this.selectedKeys[length - 1]
          // 设置表单的对应分类的等级
          this.addCateForm.cat_level = length
        } else {
          this.addCateForm.cat_pid = 0
          // 设置表单的对应分类的等级
          this.addCateForm.cat_level = 0
        }
      },
      // 添加分类
      addCate() {
        this.$refs.addCateRef.validate(async valid => {
          if (!valid) return
          const { data: res } = await this.$http.post('categories', this.addCateForm)
          if (res.meta.status !== 201) return this.$message.error('添加分类失败！')
          this.$message.success('添加分类成功！')
          this.getCateList()
          this.addCateDialogVisible = false
        })
      },
      // 删除分类
      async deleteCate(cateId) {
        const confirmResult = await this.$confirm('此操作将删除该分类，是否继续？', '提示', {
          confirmButtonText: '确定',
          cancelButtonText: '取消',
          type: 'warning'
        }).catch(err => err)
        if (confirmResult !== 'confirm') return
        const { data: res } = await this.$http.delete(`categories/${cateId}`)
        if (res.meta.status !== 200) this.$message.error('删除分类失败！')
        this.$message.success('删除分类成功！')
        this.getCateList()
      }
    }
  }
</script>

<style lang="less" scoped>
  .el-cascader {
    width: 100%;
  }
</style>
